package jhr.cms.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

@SuppressWarnings({"unchecked"})
public class Dao<T> {
	private SessionFactory sessionFactory;
	private Class<T> eclass;//实体类
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public Dao(Class<T> entity){
		this.eclass = entity;
	}
	
	/** 保存更新 */
	public T saveOrUpdate(T t){
		Session s = sessionFactory.getCurrentSession();
		try{
			s.beginTransaction();
			s.save(t);
			s.getTransaction().commit();
		}finally{
			if(s.isOpen())
				s.close();
		}
		return t;
	}
	
	/** 删除 */
	public void delete(Serializable id){
		Session s = sessionFactory.getCurrentSession();
		try{
			s.beginTransaction();
			s.delete(get(id));
			s.getTransaction().commit();
		}finally{
			if(s.isOpen())
				s.close();
		}
	}
	
	/** 查询 */
	public T get(Serializable id){
		Session s = sessionFactory.getCurrentSession();
		T t = null;
		try{
			s.beginTransaction();
			t = (T) s.get(eclass, id);
			s.getTransaction().commit();
		}finally{
			if(s.isOpen())
				s.close();
		}
		return t;
	}
	
	public List<T> find(final String hql, final int start, final int size, final Object... args){
		Session s = sessionFactory.getCurrentSession();
		List<T> list = null;
		try{
			Query q = s.createQuery(hql);
			for(int i = 0; i<args.length; i++)
				q.setParameter(i+1, args[i]);
			q.setFirstResult(start);
			q.setMaxResults(size);
			list = q.list();
		}finally{
			if(s.isOpen())
				s.close();
		}
		return list;
	}
}
